package com.Policing.lease;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.Policing.Adapter.Input_Adapter_item;
import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.bean.Input_item;
import com.Policing.misc.Accompaniment;
import com.Policing.uhf.util.DataTransfer;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.senter.iot.support.openapi.uhf.UhfD2;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Lease_add extends BaseActivity implements OnDismissListener {
    private EditText leaseholder;//租赁人
    private String url="http://"+ Ip_Set.IP+"/api/leaseAddInspect";
    private String up_url="http://"+ Ip_Set.IP+"/api/leaseAdd";
    private EditText leasing_amount;//租赁金额
    private TextView duration;//租赁时长
    private EditText Lease_note,et_num;//租赁备注，扫码
    private LinearLayout Date;
    private String id;//登录id
    private List<String> numbers = new ArrayList<>();//资产ID
    private List<Input_item> data = new ArrayList<>();
    private List<String> rfid_data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private Lease_add content;
    private ListView lv_list;
    private ImageView fh;
    private Handler handler = new Handler();
    private Button rfid_bt,upload_bt,scan_img;
    private boolean state;
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(Lease_add.this, R.raw.tag_inventoried);
    //播放声音
    private Handler accompainimentsHandler;
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    private boolean isrfid=true;
    private boolean stop_rfid =true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        content = this;
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        lv_data.clear();
        data.clear();
    }

    @Override
    public int intiLayout() {
        return R.layout.lease_add;
    }

    @Override
    public void initView() {
        fh = (ImageView) findViewById(R.id.fh);
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        rfid_bt  = (Button) findViewById(R.id.Rfid);
        upload_bt = (Button) findViewById(R.id.upload);
        scan_img = (Button) findViewById(R.id.scan_img);
        leaseholder = (EditText) findViewById(R.id.leaseholder);
        leasing_amount = (EditText) findViewById(R.id.leasing_amount);
        duration = (TextView) findViewById(R.id.duration);
        Lease_note = (EditText) findViewById(R.id.remark);
        Date  = (LinearLayout) findViewById(R.id.date);
        et_num = (EditText) findViewById(R.id.et_num);

    }

    @Override
    public void initData() {
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i=0;i<data.size();i++){
                    if (S.equals(data.get(i).getCode_number())){
                        Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!et_num.getText().toString().trim().equals("")&&et_num.length()>9){
                    if (!lv_data.contains(et_num.getText().toString().trim())){
                        post(et_num.getText().toString().trim(),"");
                    }else {
                        toastShort("此资产已存在列表");
                    }

                }else {
                    toastShort("错误的格式");
                }
            }
        });
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final DatePickDialog dialog = new DatePickDialog(Lease_add.this);
                //设置上下年分限制
                dialog.setYearLimt(20);
                //设置标题
                dialog.setTitle("选择时间");
                //设置类型
                dialog.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(java.util.Date date) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String time = sdf.format(date);
                        duration.setText(time);
                    }
                });
                dialog.show();

            }
        });
        upload_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        rfid_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isrfid==true){
                        if (UhfD2.getInstance().init() == true){
                            UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                        }
                        isrfid = false;
                    }

                }catch (Exception E){
                    Toast.makeText(content,"没有RFID模块",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (stop_rfid){
                    stop_rfid=false;
                    start_read();
                    rfid_bt.setText("停止读取");
                }else {
                    stop_rfid=true;
                    state =false;
                    rfid_bt.setText("开启RFID");
                }

            }
        });
        upload_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data.size()<=0){
                    Toast.makeText(content,"请添加资产",Toast.LENGTH_SHORT).show();
                    return;
                }
              if (leaseholder.getText().toString().trim().equals("")||leasing_amount.getText().toString().trim().equals("")||duration.getText().toString().equals("")){
                  Toast.makeText(content,"请完善数据后重试！！",Toast.LENGTH_SHORT).show();
                  return;
              }
                new AlertView(" 提示！", "是否上传数据", "取消",new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            numbers.clear();
                            for (int i =0;i<data.size();i++){
                                numbers.add(data.get(i).getCode_number());
                            }
                            updata();
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(Lease_add.this).show();

            }
        });


    }
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            for (int i=0;i<data.size();i++){
                if (scanResult.equals(data.get(i).getCode_number())){
                    Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (!lv_data.contains(scanResult)){
                post(scanResult,"");
            }else Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();

        }
    }
    public void post(final String assetNumber, final String rfid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumber",assetNumber)
                        .add("rfid",rfid); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Bitmap bitmap =null;
                                    Log.i("123123", responseData);
                                    JSONObject json = new JSONObject(responseData);
                                    if (json.getString("state").equals("1"))
                                    {
                                        lv_data.add(assetNumber);
                                        JSONObject jsonObject = json.getJSONObject("asset");
                                        String assetName = jsonObject.getString("assetName");
                                        String deptId = jsonObject.getString("deptId");
                                        String assetNumber = jsonObject.getString("assetNumber");
                                        String userId = jsonObject.getString("userId");
                                        String model = jsonObject.getString("model");
                                        String type = jsonObject.getString("type");
                                        String rfid = jsonObject.getString("rfid");
                                        if (jsonObject.getString("image").equals("")){
                                            @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                            bitmap = BitmapFactory.decodeStream(is);
                                        }else {
                                            byte [] input = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT);
                                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                        }
                                        Collections.reverse(data);
                                        data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,rfid));
                                        Collections.reverse(data);
                                        Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                                        lv_list.setAdapter(adapter_item);
                                        Toast.makeText(content,"添加成功",Toast.LENGTH_SHORT).show();


                                    }
                                    if (json.getString("state").equals("0")){

                                        Toast.makeText(content,"添加失败，请检查服务器",Toast.LENGTH_SHORT).show();

                                    }
                                    if (json.getString("state").equals("2")){

                                        Toast.makeText(content,"添加失败，此资产不存在",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("3")){
                                        Toast.makeText(content,"添加失败，资产已租用",Toast.LENGTH_SHORT).show();

                                    }
                                    if (json.getString("state").equals("4")){
                                        Toast.makeText(content,"添加失败，非闲置资产",Toast.LENGTH_SHORT).show();

                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        });

                    }
                });

            }
        }).start();

    }
    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                for (int i = 0; i<data.size();i++){
                    if (DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4).equals(data.get(i).getRfid())){
                        return;
                    }
                }
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    final String rfid = DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            post("",rfid);
                        }
                    },300);
                    trigTagAccompainiment();//播放声音
                }
            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });


    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
    private void updata() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("id",id)
                            .add("leaseUser",leaseholder.getText().toString().trim())
                            .add("leaseTime",duration.getText().toString())
                            .add("leaseAmount",leasing_amount.getText().toString().trim())
                            .add("leaseRemark",Lease_note.getText().toString().trim())
                            .add("assetNumbers",numbers.toString())
                            .build();
                    Request request = new Request.Builder()
                            .url(up_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                    Log.i("222",responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }



            }
        }.start();
    }
    private void showResponse(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getString("state").equals("1")){
                        lv_data.clear();
                        data.clear();
                        numbers.clear();
                        finish();
                        Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                        lv_list.setAdapter(adapter_item);
                        Toast.makeText(content,"提交成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(content,"提交失败,请重新提交",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void onDismiss(Object o) {

    }
}
